package edu.gyc.appshiro.controller;


import edu.gyc.appshiro.dao.RoleDao;
import edu.gyc.appshiro.model.Permission;
import edu.gyc.appshiro.model.User;
import edu.gyc.appshiro.service.PermissionService;
import edu.gyc.appshiro.service.RoleService;
import edu.gyc.appshiro.service.UserService;
import edu.gyc.appshiro.vo.PermissionVo;
import edu.gyc.appshiro.vo.UserRoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;

import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author ls
 * @since 2021-02-02
 */
@Controller
@RequestMapping("/perm")
public class PermissionController {
    @Autowired
    RoleService roleService;
    @Autowired
    UserService userService;

    @Autowired
    RoleDao roleDao;

    //用户权限查询
    @RequestMapping("/query")
    public String userquery(Model model) {

        return "/admin/userperms";
    }

    @RequestMapping("/queryperms")
    public String userPerms(Integer id, Model model) {
        List<PermissionVo> permissionVos = roleService.getUserPermissionByUid(id);
        model.addAttribute("perms", permissionVos);
        model.addAttribute("username", userService.lambdaQuery().eq(User::getUid, id).one().getUsername());
        return "/admin/userperms";
    }

    @Autowired
    PermissionService permissionService;

    @RequestMapping("/list")
    public String list(Model model) {
        List<Permission> permissions = permissionService.list();
        model.addAttribute("perms", permissions);
        return "/admin/perms";
    }

    @PostMapping("/add")
    public String add(Permission permission, Model model) {
        String msg = "";
        Permission tempPermission =permissionService
                .lambdaQuery()
                .eq(Permission::getUrl,permission.getUrl())
                .or()
                .eq(Permission::getPermission,permission.getPermission())
                .one();
        if (tempPermission != null) {
            msg = "权限路径或者权限已经存在！";
        }else {
            permissionService.save(permission);
            msg = "权限添加成功！";
        }
        model.addAttribute("msg", msg);
        return "/perm/list";
    }

    @RequestMapping("/del")
    public String del(Integer id ,Model model) {
        String msg = "";
       boolean r= permissionService.removeById(id);

        if (r) {
            msg = "权限删除成功！";
        }else {

            msg = "权限删除失败！";
        }
        model.addAttribute("msg", msg);
        return "/perm/list";
    }
}

